
#include "ConfigFile.h"
#include <fstream>
#include <windows.h>
#include <tchar.h>

using namespace config;

ConfigFile::ConfigFile()
{

}

ConfigFile::ConfigFile(const std::string filename)
{
	read( filename );
}


ConfigFile::~ConfigFile()
{

}

// service string functions.

void trim( const std::string & s, int &first, int &last )
{
	int i = first;
	while( i < last && _istspace(s[i]) ){ 
		i++;
	}
	first = i;

	i = last;
	while( i > first && _istspace(s[i]) ){ 
		i--;
	}
	last = i;
}

void ConfigFile::read( const std::string &filename )
{
	std::ifstream fin;
	//char buf[500];

	fin.open( filename.c_str()  );
	if( !fin.is_open() )
	{
		throw ConfigNotFound( filename );
	}
	
	std::string s;
	fin.seekg (0, std::ios::beg);
	while( !fin.eof() ){
		std::getline( fin, s );
		//MessageBox( 0, s.c_str(),0,0);
		parseLine( s );
	}
	
}

void ConfigFile::parseLine( const std::string & s )
{
	using std::string;
	int first = 0;
	int last = s.length()-1;

	// Erase comments.
	int pos = s.find( _T('#') );
	if ( pos != string::npos ){
		last = max( 0, pos - 1 );
	}

	// Erase leading and trailing whitespaces.
	trim( s, first, last );

	// Pick out equal sign.
	pos = s.find( _T('='), first );
	// If none - error.
	if ( pos == string::npos ){
		return;
	}

	// Extract param name.
	// trim first.
	int paramlast = pos-1;
	trim( s, first, paramlast );
	std::string sParam = s.substr( first, paramlast - first + 1 );

	// Extract param value.
	pos++;
	trim( s, pos, last );
	std::string sValue = s.substr( pos, last - pos+1 );

	mParams[ sParam ] = sValue;
}


inline std::string f( const std::string & s )
{
	return s;
}

void ConfigFile::get_value(const std::string &param, std::string *value, const std::string &defval)
{
	get_value( param, value, defval, f );
}

ConfigFile::iterator ConfigFile::begin()
{
	return mParams.begin();
}

ConfigFile::iterator ConfigFile::end()
{
	return mParams.end();
}


ConfigFile::const_iterator ConfigFile::begin() const
{
	return mParams.begin();
}

ConfigFile::const_iterator ConfigFile::end() const
{
	return mParams.end();
}

